package com.yuelao.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author FLY
 * @version v1.0
 * @project yuelao-server
 * @date 2017/9/13 16:50
 * @修改记录 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 */
@Component
public class RedisLock {
    @Autowired
    private JedisPool jedisPool;

    private static final String TASK_KEY = "redis_lock_task_";

    private static final String SYN_KEY = "redis_lock_syn_";

    private static final long TASK_OUT_TIME = 23 * 60 * 60 * 1000;

    /**
     * 定时任务锁
     *
     * @param taskKey
     * @param curTime
     * @return
     */
    public boolean taskLock(String taskKey, long curTime) {
        Jedis jedis = jedisPool.getResource();
        String setKey = TASK_KEY + taskKey;
        long var0 = jedis.setnx(setKey, curTime + "");
        if (var0 == 1) {
            long setTime0 = Long.valueOf(jedis.get(setKey));
            // 验证是对否是此线程加的锁
            if (curTime == setTime0) {
                return true;
            }
        }
        long setTime1 = Long.valueOf(jedis.get(setKey));
        if (curTime > setTime1 + TASK_OUT_TIME) {
            jedis.getSet(setKey, curTime + "");
            long setTime2 = Long.valueOf(jedis.get(setKey));
            if (curTime == setTime2) {
                return true;
            }
        }
        return false;
    }

    /**
     * 释放任务锁
     *
     * @param taskKey
     */
    public void unTaskLock(String taskKey) {
        Jedis jedis = jedisPool.getResource();
        jedis.del(TASK_KEY + taskKey);
    }

}
